package com.xlx.ui.service.error.errorImpl;


import com.xlx.ui.domain.VO.ResultBody;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
/**
 * @Description:处理全局异常类
 * @author: 张川
 * @date: 2020-06-04 10:52
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理自定义的业务异常
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = BizException.class)
    @ResponseBody
    public ResultBody bizExceptionHandler(HttpServletRequest req, BizException e){
        log.error("发生业务异常！原因是：{}",e.getErrorMsg());
        return ResultBody.error(e.getErrorCode(),e.getErrorMsg());
    }


    /**
     * 无效的参数
     * @param exception
     * @return
     */
//    @ExceptionHandler(ValidationException.class)
//    public ResultBody handle(ValidationException exception) {
//        log.info("无效的参数:"+exception.getMessage());
//        Map error = new HashMap<>();
//        if(exception instanceof ConstraintViolationException){
//            ConstraintViolationException exs = (ConstraintViolationException) exception;
//            Set<ConstraintViolation<?>> violations = exs.getConstraintViolations();
//            for (ConstraintViolation<?> item : violations) {
//                error.put(item.getPropertyPath().toString(),item.getMessageTemplate());
//            }
//        }
//        return ResultBody.error(ResponseCodeEnum.PARAMETER_INVALID, JSONUtil.parseObj(error));
//    }

    /**
     * 请求类型异常
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = HttpRequestMethodNotSupportedException.class)
    public ResultBody HttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e){
        log.info("错误的请求类型:",e.getMethod());
        return  ResultBody.error(ResponseCodeEnum.REQUEST_TYPE_INVALID,e.getMessage());
    }


    /**
     * 处理空指针的异常
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value =NullPointerException.class)
    @ResponseBody
    public ResultBody exceptionHandler(HttpServletRequest req, NullPointerException e){
        log.error("发生空指针异常！原因是:",e);
        return ResultBody.error(ResponseCodeEnum.NULL_SERVER_ERROR,e.getMessage());
    }


    /**
     * 处理其他异常
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value =Exception.class)
    @ResponseBody
    public ResultBody exceptionHandler(HttpServletRequest req, Exception e){
        log.error("未知异常！原因是:",e);
        return ResultBody.error(ResponseCodeEnum.INTERNAL_SERVER_ERROR,e.getMessage());
    }



}

